import xlrd
import random
from docx import Document
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

workbook = xlrd.open_workbook("examination.xls")
sheet = workbook.sheet_by_index(0)


class Question:
    pass


def create_question():
    question_list = []
    for i in range(sheet.nrows):
        if i > 1:
            obj = Question()
            obj.subject = sheet.cell_value(i, 1)
            obj.question_type = sheet.cell_value(i, 2)
            obj.option = []
            obj.option.append(sheet.cell_value(i, 3))
            obj.option.append(sheet.cell_value(i, 4))
            obj.option.append(sheet.cell_value(i, 5))
            obj.option.append(sheet.cell_value(i, 6))
            obj.score = sheet.cell_value(i, 7)
            obj.question_type = sheet.cell_value(i, 2)
            question_list.append(obj)
    # 将序列的所有元素随机排列
    random.shuffle(question_list)
    return question_list

# 生成试卷
def create_paper(file_name, paper_name, question_list):
    document = Document()
    # 页眉
    section = document.sections[0]
    header = section.header
    p1 = header.paragraphs[0]
    p1.text = paper_name
    # 页脚
    footer = section.footer
    p2 = footer.paragraphs[0]
    p2.text = "内部试题，禁止泄露。"
    # 试卷基本信息
    title = document.add_heading(paper_name, level=1)
    title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    p3 = document.add_paragraph()
    p3.add_run("姓名：_______")
    p3.add_run("所属部门：_______")
    p3.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

    # 试题信息
    for question in question_list:
        subject = document.add_paragraph(style="List Number")
        # subject.add_run("%s. " % num)
        run = subject.add_run(question.subject)
        run.bold = True
        subject.add_run("[%s]分 ：" % str(question.score))
        # 打乱选项
        random.shuffle(question.option)
        for index, option in enumerate(question.option):
            document.add_paragraph(("ABCD")[index] + str(option))
    document.save(file_name + ".doc")


for i in range(3):

    question_list = create_question()
    create_paper("paper" + str(i + 1), "计算机等级（初级）理论考试试题", question_list)
